# -*- coding: utf-8 -*-
import cgi
import os
import sys
import datetime
import time
import wsgiref.handlers
import string

from control import *

from time import strftime, localtime 
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from loginTool import login_required

class User_PhotoLib(db.Model): #//用户订阅图库表
      userName = db.StringProperty(multiline=True) #//用户名
      photoLibCode = db.StringProperty(multiline=True)#//图库编号
      photoLibType = db.StringProperty(multiline=True)#//图库类型:1、系统图库，2、用户图库,3、临时图库，
      lastUpdateTime = db.DateTimeProperty(auto_now_add=True)#//上次更新时间

class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))

class User_PhotoLibList(PublicPage):
  @login_required
  def get(self):
      searchType = self.request.get('searchType')
      
      userPhotoLibs = db.GqlQuery("SELECT * FROM User_PhotoLib ORDER BY userName,photoLibType ASC ")
      
      if searchType=='':
          users = db.GqlQuery("SELECT * FROM User ORDER BY userName ASC ")
      else:
          users = db.GqlQuery("SELECT * FROM User WHERE userName>=:1 AND userName<=:2",searchType,u""+searchType+"" + u"\ufffd")
      
      AllUserLibs = []
      for user in users:
            if user.userName:
                  c = ['','1','','','2','','','3','','']
                  isHaveName = 0
                  minTime = datetime.datetime(1010, 9, 9, 11, 45, 49, 125000)
                  for userPhotoLib in userPhotoLibs:
                        if user.userName == userPhotoLib.userName:
                              if isHaveName == 0:
                                    c[0] = userPhotoLib.userName
#                                    c[7] = minTime
                                    isHaveName = 1
                              if userPhotoLib.photoLibType=='1':
                                    c[2] = userPhotoLib.photoLibCode
                                    c[3] = userPhotoLib.lastUpdateTime
#                                    c[7] = max(a,c[7])
                              if userPhotoLib.photoLibType=='2':
                                    c[5] = userPhotoLib.photoLibCode
                                    c[6] = userPhotoLib.lastUpdateTime
#                                    c[7] = max(b,c[7])
                              if userPhotoLib.photoLibType=='3':
                                    c[8] = userPhotoLib.photoLibCode
                                    c[9] = userPhotoLib.lastUpdateTime
#                                    c[7] = max(e,c[7])
                  if c[0]=='':
                        c[0] = user.userName
                        
                  AllUserLibs.append(c)
      template_values = {'AllUserLibs':AllUserLibs,'searchType':searchType}
      self.render('template/userPhotoLib/userPhotoLibList.html',template_values)
#      self.render('html/userPhotoLibManage/userPhotoLibList.html',template_values)
  @login_required
  def post(self):
      searchType = self.request.get('searchType')
      self.redirect('/user_PhotoLibList?searchType=%s' %searchType)

class User_PhotoLibAdd(PublicPage):
  @login_required
  def get(self):
      userName = self.request.get('userName')
      sysPhotoLib = self.request.get('sysPhotoLib')
      userPhotoLib = self.request.get('userPhotoLib')
      temPhotoLib = self.request.get('temPhotoLib')
      searchType = self.request.get('searchType')

      if sysPhotoLib!='' and userPhotoLib!='' and temPhotoLib!='':
            self.response.out.write('<script>alert("用户图库已全部存在，不能再添加！");history.back(-1);</script>')
            return
      else:
            photoLibTypeList=['','','']
            if sysPhotoLib=='':
                  photoLibTypeList[0]='1'
            if userPhotoLib=='':
                  photoLibTypeList[1]='2'
            if temPhotoLib=='':
                  photoLibTypeList[2]='3'
                  
            userLibList = set()
            userPhotoLibs = db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1",userName)
            for userPhotoLib in userPhotoLibs:
                  if userPhotoLib.photoLibCode:
                        userLibList.add(userPhotoLib.photoLibCode)
            if searchType:
                photoLibs = db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibName>=:1 AND photoLibName<=:2",searchType,u""+searchType+"" + u"\ufffd")
            else:
                photoLibs = db.GqlQuery("SELECT * FROM PhotoLib ")
            pLists = []
            for photoLib in photoLibs:
                if str(photoLib.photoLibCode) not in userLibList:
                    pLists.append(photoLib)
                              
      template_values = {'pLists':pLists,"userName":userName,"photoLibTypeList":photoLibTypeList,'searchType':searchType,'sysPhotoLib':sysPhotoLib,'userPhotoLib':userPhotoLib,'temPhotoLib':temPhotoLib}
      self.render('template/userPhotoLib/photoLibList.html',template_values)
#      self.render('html/userPhotoLibManage/photoLibList.html',template_values)
  @login_required
  def post(self):
      greeting = User_PhotoLib()
      greeting.userName = self.request.get('userName')
      greeting.photoLibCode = self.request.get('photoLibCode')
      greeting.photoLibType = self.request.get('photoLibType')
      greeting.put()
      self.redirect('/user_PhotoLibList')

class U_PhotoLibList(PublicPage):
  @login_required
  def get(self):
      userPhotoLibs = db.GqlQuery("SELECT * FROM User_PhotoLib ORDER BY userName,photoLibType ASC ")
      for userPhotoLib in userPhotoLibs:
            self.response.out.write(userPhotoLib.userName+"  ")
            self.response.out.write(userPhotoLib.photoLibCode+"  ")
            self.response.out.write(userPhotoLib.photoLibType+"  ")
            self.response.out.write(userPhotoLib.lastUpdateTime)
           # db.delete(userPhotoLib)

class User_PhotoLibDelete(PublicPage):
  @login_required
  def get(self):
      userName = self.request.get('userName')
      photoLibType = self.request.get('photoLibType')
      userPhotoLibs = db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1 AND photoLibType=:2",userName,photoLibType)
      for userPhotoLib in userPhotoLibs:
            db.delete(userPhotoLib)
      self.redirect('/user_PhotoLibList')
      
class User_PhotoLib_PhotoList(PublicPage):
  @login_required
  def get(self):
      userName = self.request.get('userName')
      userPhotoLibs = db.GqlQuery("SELECT * FROM User_PhotoLib WHERE userName=:1",userName)
      user_PhotoLib_Photos=['','','']
      sysPhotoList = []
      userPhotoList = []
      temPhotoList = []
      for userPhotoLib in userPhotoLibs:
            if userPhotoLib.photoLibCode:
                  photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoLibCode=:1 AND status='1' ORDER BY lastUpdateTime  ASC" ,userPhotoLib.photoLibCode)
                  if userPhotoLib.photoLibType=='1':
                        for photoLib_Photo in photoLib_Photos:
                              if photoLib_Photo.photoCode:
                                    images=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",photoLib_Photo.photoCode)
                                    #for image in images:
                                    sysPhotoList.append(images)
                        user_PhotoLib_Photos[0] = sysPhotoList
                  if userPhotoLib.photoLibType=='2':
                        for photoLib_Photo in photoLib_Photos:
                              if photoLib_Photo.photoCode:
                                    images=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",photoLib_Photo.photoCode)
                                    #for image in images:
                                    userPhotoList.append(images)
                        user_PhotoLib_Photos[1] = userPhotoList
                  if userPhotoLib.photoLibType=='3':
                        for photoLib_Photo in photoLib_Photos:
                              if photoLib_Photo.photoCode:
                                    images=db.GqlQuery("SELECT * FROM Images WHERE photoCode=:1",photoLib_Photo.photoCode)
                                    #for image in images:
                                    temPhotoList.append(images)
                        user_PhotoLib_Photos[2] = temPhotoList
      template_values = {'user_PhotoLib_Photos':user_PhotoLib_Photos,"userName":userName,}
      self.render('template/userPhotoLib/user_PhotoLib_PhotoList.html',template_values)
#      self.render('html/userPhotoLibManage/user_PhotoLib_PhotoList.html',template_values)
